//
//  AudioPlayer.swift
//  growth-diary
//
//  Created by weibin on 2022/7/22.
//

import AVFoundation

class AudioPlayer: NSObject,AVAudioPlayerDelegate {
    
    //单列
    static let shared = AudioPlayer()
    //播放器
    var audioPlayer:AVAudioPlayer = AVAudioPlayer()
    //播放完毕
    var completePlayingBlock: (()->Void)?
    
    //MARK:初始化播放器
    func play(path: String, isAutoplay: Bool = true) {
        let session = AVAudioSession.sharedInstance()
        //在音频播放前，首先创建一个异常捕捉语句
        do {
            //启动音频会话管理，此时会阻断后台音乐播放
            try session.setActive(true)
            //设置音频播放类别，表示该应用仅支持音频播放
            try session.setCategory(AVAudioSession.Category.playback)
            
            //将字符串路径转化为网址路径
            let soundUrl = URL(fileURLWithPath: path)
            
            try audioPlayer = AVAudioPlayer(contentsOf:soundUrl)
            //为音频播放做好准备
            audioPlayer.prepareToPlay()
            //设置音量
            audioPlayer.volume = 1.0
            //是否循环播放
            //audioPlayer.numberOfLoops = -1
            audioPlayer.delegate = self
            if isAutoplay {
                play()
            }
        } catch {
            print(error)
        }
    }
    
    //MARK:开始播放
    func play() {
        if audioPlayer.duration > 0 {
            audioPlayer.play()
        }
    }
    
    //MARK:暂停播放
    func pause() {
        if audioPlayer.duration > 0 {
            audioPlayer.pause()
        }
    }
    
    //MARK:停止播放
    func stop() {
        if audioPlayer.duration > 0 {
            audioPlayer.stop()
        }
        completePlayingBlock?()
    }
    
    //MARK:播放时长
    func currentTime() -> (TimeInterval) {
        return audioPlayer.currentTime
    }
    
    //MARK:音频时长
    func duration() -> (TimeInterval) {
        return audioPlayer.duration
    }
    
    //MARK:修改播放进度
    func playWithPercent(percent:Double) {
        if audioPlayer.duration > 0 {
            audioPlayer.currentTime = audioPlayer.duration * percent
        }
    }
    
    //MARK:修改音量大小
    func updateVolume(volume:Float) {
        audioPlayer.volume = volume
    }
    
    //MARK:播放进度
    func percent() -> (Float) {
        var percent:Float = 0
        if audioPlayer.duration > 0  {
            percent = Float(audioPlayer.currentTime/audioPlayer.duration)
        }
        return percent
    }
    
    //MARK:播放完毕
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        self.stop()
    }
}
